package leetcode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

//树的遍历迭代的关键是栈 stack
public class LeetCode144 {

    List<Integer> result = new ArrayList<>();

    public List<Integer> preorderTraversal1(TreeNode root) {
        walk(root);
        return result;
    }

    private void walk(TreeNode node) {
        if (node == null)
            return;
        result.add(node.val);
        walk(node.left);
        walk(node.right);
    }
//------------------------------------------------------------------

    //非递归
    public List<Integer> preorderTraversal(TreeNode root) {
        LinkedList<TreeNode> stack = new LinkedList<>();
        Stack<Integer> output = new Stack<>();
        if (root == null) {
            return output;
        }

        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pollLast();
            output.add(node.val);
            if (node.right != null) {
                stack.add(node.right);
            }
            if (node.left != null) {
                //先使用左节点
                stack.add(node.left);
            }
        }
        return output;
    }
}
